package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.UserInfoExtendDTO;
import com.xuedongzhilian.dto.UserDTO;
import com.xuedongzhilian.service.IUserManagementService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 用户管理控制器（学动智联系统）
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/user/manage")
public class UserManagementController {

    @Resource
    private IUserManagementService userManagementService;

    /**
     * 微信快捷登录
     */
    @PostMapping("/wechat/login")
    public Result wechatLogin(@RequestParam("code") String code, HttpSession session) {
        log.info("Received wechat login request with code: {}", code);
        Result result = userManagementService.wechatLogin(code, session);
        log.info("Wechat login result: {}", result);
        return result;
    }

    /**
     * 获取用户扩展信息
     */
    @GetMapping("/info")
    public Result getUserInfo() {
        log.info("Received get user info request");
        // 获取当前登录用户ID
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            log.warn("User not logged in when trying to get user info");
            return Result.fail("用户未登录");
        }
        Long userId = user.getId();
        UserInfoExtendDTO userInfoExtendDTO = userManagementService.getUserInfoExtend(userId);
        return Result.ok(userInfoExtendDTO);
    }

    /**
     * 更新用户扩展信息
     */
    @PutMapping("/info")
    public Result updateUserInfo(@RequestBody UserInfoExtendDTO userInfoExtendDTO) {
        log.info("Received update user info request");
        // 获取当前登录用户ID
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            log.warn("User not logged in when trying to update user info");
            return Result.fail("用户未登录");
        }
        Long userId = user.getId();
        return userManagementService.updateUserInfoExtend(userId, userInfoExtendDTO);
    }
}